package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;




@Slf4j
@WebFilter(filterName = "loginCheckFilter")
public class LoginCheckFilter implements Filter {
  /*匹配路径*/
   public final AntPathMatcher pathMatcher= new AntPathMatcher();
   /*授权的url*/
    private String[] authUrl=new String[]{
           "/employee/login",
           "/employee/logout",
           "/backend/**",
           "/front/**",
           "/common/**",
           "/user/sendMsg", // 移动端的发送短信
           "/user/login",
           "/doc.html",
           "/webjars/**",
           "/swagger-resources",
           "/v2/api-docs"// 移动端的登录
   };
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException{
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        /*获取本次请求的url*/
        String requestURI = request.getRequestURI();
        log.info("请求拦截判断器",requestURI);
        /*判断本次请求是否需要处理*/
        boolean isAuth=checkAuthUrl(requestURI);
        /*如果不需要直接放行*/
        if (isAuth){
            log.info("[登录检查过滤器],允许放行");
            filterChain.doFilter(request,response);
            return;
        }/*判断登录的状态*/
     if(request.getSession().getAttribute("employee")!=null){
         log.info("[已登录]",request.getSession().getAttribute("employee"));
         Long empId=(Long)request.getSession().getAttribute("employee");
         BaseContext.setCurrentId(empId);
         //判断移动端是否登录过(后台登录)
         filterChain.doFilter(request,response);
         return;
     }
         if (request.getSession().getAttribute("user" )!= null) {
             log.info("[登录检查过滤器],移动端已登录，允许通过");
             Thread thread = Thread.currentThread();
             log.info("[登录检查过滤器],移动端已登录，允许通过: 当前线程ID:{}",thread.getId());
             Long empId = (Long)request.getSession().getAttribute("user");             BaseContext.setCurrentId(empId);
             filterChain.doFilter(request,response);
             return;
         }
         log.info("[登录失败.未授权]");
         /*如果未登录则返回为登录的结果
          * 注意啊返回信息必须是NOTLOGIN  否则客户端无法跳转   因为前端键查的字段是这个*/
         response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
     }


   private boolean checkAuthUrl(String requestURI) {
       for (String url : authUrl) {
           if (pathMatcher.match(url,requestURI)){
               return true;
           }

       }return false;
    }



}
